import { post, get } from '@/api/ajax'
import API from '@/api/apis'
import { Commit } from 'vuex'
import { getToken, setToken, removeToken } from '@/utils/auth'

export interface State {
  token: string
  // 用户名
  name: string
  // 头像
  icon: string
  // 是否获取到用户数据
  isGetUser: boolean
}

export interface UserInfo {
  icon: string
  pass: string
  name: string
}

const initState: State = {
  token: getToken(),
  // 用户名
  name: '',
  // 头像
  icon: '',
  // 是否获取到用户数据
  isGetUser: false,
}

const mutations = {
  // 设置token
  SET_TOKEN: (state: State, token: string) => {
    state.token = token
    if (token) {
      setToken(token)
    } else {
      removeToken()
    }
  },
  // 设置用户数据
  SET_USER_INFO: (state: State, userInfo: UserInfo) => {
    if (userInfo) {
      state.name = userInfo.name
      state.icon = userInfo.icon
      state.isGetUser = true
    } else {
      state.name = ''
      state.icon = ''
      state.isGetUser = false
    }
  },
}

const actions = {
  // 登录
  LOGIN(context: { commit: Commit }, userInfo: UserInfo) {
    return new Promise((resolve, reject) => {
      post(API.auth.login, userInfo).then((data: any) => {
        context.commit('SET_TOKEN', data.token)
        context.commit('SET_USER_INFO', data)
        resolve()
      }).catch((error) => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  GET_USER_INFO(context: { commit: Commit }) {
    return new Promise((resolve, reject) => {
      get(API.auth.getUserInfo).then((data) => {
        context.commit('SET_USER_INFO', data)
        resolve(data)
      }).catch((error) => {
        reject(error)
      })
    })
  },
  // 修改用户数据
  MODIFY_USER_DATA(context: { }, userInfo: UserInfo) {
    return new Promise((resolve, reject) => {
      post(API.auth.modify, {
        icon: userInfo.icon,
        pass: userInfo.pass,
        name: userInfo.name,
      }).then((data) => {
        resolve(data)
      }).catch((err) => {
        reject(err)
      })
    })
  },
  // 登出
  LOG_OUT(context: { commit: Commit }) {
    context.commit('SET_TOKEN', null)
    context.commit('SET_USER_INFO', null)
    return Promise.resolve()
    // return new Promise((resolve, reject) => {
    //   get(API.admin.logOut).then(() => {
    //     commit('SET_TOKEN', null)
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },
  // 前端 登出
  FED_LOG_OUT(context: { commit: Commit }) {
    context.commit('SET_TOKEN', null)
    context.commit('SET_USER_INFO', null)
  },
}

export default {
  state: initState,
  actions,
  mutations,
}
